<template>
  <el-container>
    <el-main>
      <el-form ref="payable" :model="form" :rules="rules" label-width="80px">
        <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
          <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">对账信息</span>
        </div>
        <div style="display: flex">
          <el-form-item label="供应商名"  prop="supplierId">
            <el-select  style="width: 201px" v-model="supplierName"  value-key="id"  :filter-method="remoteMethod"  filterable placeholder="请选择供应商" @change="selectSupplier">
              <el-option
                v-for="item in suppliers"
                :key="item.id"
                :label="item.name"
                style="width: 600px"
                :value="item">
                <div style="display: flex">
                  <span style="float: left;width: 80px;overflow: hidden;text-overflow: ellipsis;">{{ item.name }}</span>
                  <span style="width: 100px;overflow: hidden;text-overflow: ellipsis;">{{ item.phone }}</span>
                  <div style="width: 200px;">
                    <span style="color: #8492a6; font-size: 8px;">{{item.areaName}}{{item.address}}</span>
                  </div>
                </div>
              </el-option>
              <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                <div class="elOption" @click="toSearchSupplier">搜索供应商</div>
                <!--<div class="elOption1" @click="toAddSupplier">新增供应商</div>-->
              </div>
              <div style="height: 30px"></div>
            </el-select>
          </el-form-item>
          <el-form-item label="对账日期">
            <el-date-picker
              style="width: 201px"
              v-model="form.orderDate"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>

        </div>
        <div style="display: flex">
          <el-form-item label="备注留言" prop="address" >
            <el-input v-model="form.address" style="width: 480px"/>
          </el-form-item>

        </div>

        <div class="product_header_name" style="">
          <span style="font-size: 18px;color:#409EFF;margin: 10px 10px;">应付款明细</span>
        </div>
        <el-table
          ref="payableSupplierTable"
          :data="payableSupplierList"
          :height="'52vh'"
          :summary-method="getSummaries"
          show-summary
          border
          stripe
          @select="handleSelectionChange"
          @select-all="handleSelectionAllChange"
          @selection-change="selectionChangeFn"
        >
          <el-table-column type="selection" align="center" width="55" />
          <el-table-column label="订单日期" align="center" width="160">
            <template slot-scope="scope">
              <span>{{ scope.row.orderDate | datetimeFormatter }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单号" align="center" prop="orderSn" width="100" />
          <el-table-column label="供应商名称" align="center" prop="supplierName" width="200" />
          <el-table-column label="付款状态" align="center" width="100" >
            <template slot-scope="scope">
              <span>{{ scope.row.status | watchStatus }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单据类型" width="100" align="center" >
            <template slot-scope="scope">
              <span>{{scope.row.orderType | watchOrderType}}</span>
            </template>
          </el-table-column>
          <el-table-column label="应付金额" align="center" prop="amount" width="120" />
          <el-table-column label="已付金额" align="center" prop="amountPaid" width="120" />
          <el-table-column label="未付金额" align="center" prop="restAmount" width="120" />
          <el-table-column label="支付方式" align="center" prop="paymentPluginName" width="150" />
          <el-table-column label="备注" align="center" prop="memo" width="150" />
        </el-table>

        <div style="display: flex;justify-content: space-between;">
          <!--<el-input v-model="unpayAmount" readonly />-->
          <div style="margin-top: 30px;">
            <span style="font-size: 16px;color: red;">对账金额：{{unpayAmount}}</span>
          </div>
          <!--<el-footer class="el-footerBox" style="margin-top: 10px;">-->
          <div style="margin-top: 30px;">
            <el-button v-permission="['verify1.add']" type="primary" :loading="saveClicked" @click="saveClick" :disabled="selectionChange.length===0">保 存</el-button>
          </div>
          <!--</el-footer>-->
          <!--<el-button type="primary" style="margin-top: 20px" v-permission="['purchasein.in']" :loading="clicked" @click="saveInstockClick('purchaseForm')">保存并入库</el-button>-->
          <!--<el-button type="success" style="margin-top: 20px" v-permission="['purchase.audit']" :loading="clicked" @click="saveConfirmClick('purchaseForm')">保存并确认</el-button>-->
          <!--<el-button  style="margin-top: 20px" :loading="clicked" @click="saveClick('purchaseForm')">保存至草稿</el-button>-->
        </div>
        </div>
      </el-form>
      <el-dialog
        title="查找供应商"
        :visible.sync="supplierVisible"
        width="950px"
        v-el-drag-dialog
        append-to-body
        :before-close="supplierClose">
        <div style="position: relative;height: 63vh;overflow: auto">
          <supplierTable :key="times"  @doubleSupplier="doubleSupplier"></supplierTable>
        </div>
      </el-dialog>
    </el-main>

  </el-container>
</template>
<script>
  import {EventBus} from '@/api/eventBus'
  import supplierTable from '../../components/SupplierTable/supplierList'
  import loadMore from '@/utils/loadMore.js'
  import { list as payableList} from '@/api/payable'
  import { list,update,find,save } from '@/api/supplierVerify'
  import { list as supplierList } from '@/api/supplier'
  import Pagination from '@/components/Pagination'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import {
    getMenuTree
  } from '@/api/sysMch.js'
  import utils from '../../utils/utils.js'
  import ElRow from "element-ui/packages/row/src/row";
  export default {
    name: 'supplierVerify-list',
    directives: { loadMore, permission ,elDragDialog},
    components: {
      ElRow,
      Pagination,supplierTable },
    filters: {
      watchStatus(val) {
        if (val === 0 || val === 1) {
          return '待付款'
        } else if (val === 1) {
          return '部份付款'
        } else if (val === 2) {
          return '已完成'
        }
      },
      watchOrderType (val) {
        if (val == 0) {
          return '采购单'
        } else if (val == 1) {
          return '退货单'
        }
      }
    },
    watch:{ // 只要路由发生变化就重新获取数据
      $route (newVal, val) {
        if (newVal.name=='supplierVerify-edit' && newVal.query.id!=this.form.id) {
          this.form.id = newVal.query.id;
          this.loadData();
        }
      }
    },
    data() {
      return {
        suppliers: [],
        payableList: [],
        hasSelectList: [],
        queryType: true,
        supplierQuery:'',
        total: 0,
        times:'',
        pageNum: 1,
        supplierVisible:false,
        pageSize: 20,
        supplierName: '',
        statusOptions: [
          { label: '全部', value: '' },
          { label: '待付款', value: 0 },
          // { label: '部份付款', value: 1 },
          { label: '已完成', value: 2 }
        ],
        paymentPluginName: '',
        maxAmount: 0,
        unpayAmount: 0,
        collectAmount: '',
        form: {
          id: '',
          enterpriseId:'',
          sn: '',
          amount:'',
          status:'',
          supplierId: '',
//          supplierName: '',
          type: 1,
          memo: '',
          orderDate: '',
          itemList: [],
        },
        payableSupplierList: [],
        selectionChange: [],
        itemList: [],
        saveClicked: false,
        curHeight: null,
        rules: {
          supplierName:[
            {required: true, message: '请选择供应商', trigger: 'blur'},
          ],
          supplierId: [
            {required: true, message: '供应商不能为空', trigger: 'blur'},
          ],
          orderDate: [
            {required: true, message: '业务日期不能为空', trigger: 'blur'},
          ],
        },
        pickerOptions: {// 时间快捷选择
          shortcuts: [{
            text: '昨天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        }
      }
    },
    created() {
      this.form.id = this.$route.query.id;
      this.loadSupplier("");
      this.loadData();
    },
    mounted() {
      this.comeIn()
      this.beforeMount()
    },
    methods: {
      doubleSupplier(data){
        this.supplierName=data.name
        this.form.supplierId=data.id
        this.supplierVisible=false
      },
      supplierClose(){
        this.supplierVisible=false
      },
      toSearchSupplier(){
        this.times=new Date().getSeconds()
        this.supplierVisible=true
      },

      loadPayable(id) {debugger
//        const keyword = Object.assign({}, this.query)
//        if(utils.isNull(keyword.date)){
//          keyword.date = []
//        }
        const params = new URLSearchParams()
        params.append('pageNum', this.pageNum)
        params.append('pageSize', this.pageSize)
        if (this.form.supplierId != '')
          params.append('supplierId', this.form.supplierId)
        params.append('status', 0)
        this.maxAmount = 0
        payableList(params).then(res => {
          this.payableSupplierList = res.data.data.map(item => {
            item.amount = Number(item.amount).toFixed(2)
            item.amountPaid = Number(item.amountPaid).toFixed(2)
            item.restAmount = (item.amount - item.amountPaid).toFixed(2)
            item.submitAmount = ''
            this.maxAmount += Number(item.restAmount)
            return item
          })
          const index = this.payableSupplierList.findIndex(item => { return item.id === id })
          index !== -1 && this.$nextTick(() => {
            this.$refs.payableSupplierTable.toggleRowSelection(this.payableSupplierList[index])
            this.payableSupplierList[index].submitAmount = this.payableSupplierList[index].restAmount
          })

          this.$nextTick(()=>{
            this.payableSupplierList.forEach(row => {
              if(this.hasSelectList.indexOf(row.id) >= 0){
                this.$refs.payableSupplierTable.toggleRowSelection(row,true);
              }
            })
          })

        }).catch(err => { console.log(err) })

      },
      collectAmountInput() { // 批量添加本次付款
        if (this.collectAmount <= 0) {
          // this.$message({ message: '付款金额不能小于1' })
          this.$refs.payableSupplierTable.clearSelection()
          this.collectAmount = ''
        } else if (this.collectAmount > this.maxAmount) {
          this.collectAmount = Number(this.maxAmount).toFixed(2)
        }
        let content = this.collectAmount
        this.$refs.payableSupplierTable.clearSelection()
        this.payableSupplierList.forEach((item, index) => {
          item.submitAmount = content - item.restAmount >= 0 ? Number(item.restAmount).toFixed(2) : Number(content).toFixed(2)
          if (item.submitAmount > 0) { // 本次付款大于0则勾选
            this.$refs.payableSupplierTable.toggleRowSelection(this.payableSupplierList[index])
          } else {
            item.submitAmount = ''
          }
          content -= item.restAmount
          content = content >= 0 ? content : 0 // 防止负数
        })
      },
      selectionChangeFn(data) {
        this.selectionChange = data
      },
      handleSelectionChange(data) {
        this.selectionChange = data;
        this.unpayAmount = 0;
        this.selectionChange.forEach(item1 => {
          this.unpayAmount = this.unpayAmount + (Number(item1.amount) - Number(item1.amountPaid));
          const index = this.payableSupplierList.findIndex(item2 => {
            return item1.id === item2.id && (item2.submitAmount === '' || item2.submitAmount === '0.00')
          })
          if (index !== -1) {
            this.payableSupplierList[index].submitAmount = this.payableSupplierList[index].restAmount
          }
        })
        this.unpayAmount = this.unpayAmount.toFixed(2);
      },
      handleSelectionAllChange(data) {
        this.selectionChange = data;
        this.unpayAmount = 0;
        this.selectionChange.forEach(item1 => {
          this.unpayAmount = this.unpayAmount + (Number(item1.amount) - Number(item1.amountPaid));
        });
        this.unpayAmount = this.unpayAmount.toFixed(2);
        this.payableSupplierList.forEach(item => {
          if (item.submitAmount !== '' || item.submitAmount !== '0.00') {
            item.submitAmount = item.restAmount
          }
        })
      },
      loadData(){
        var _this = this;
        find(this.$route.query.id).then(response => {
            debugger
          _this.supplierName=response.data.verify.supplierName;
          _this.form = response.data.verify;

          _this.hasSelectList = [];
          response.data.verify.itemList.forEach(function (item) {
            _this.hasSelectList.push(item.verifyItemId);
          })
          console.log("supplierId==" + _this.form.supplierId);
          console.log("supplierName==" + _this.supplierName);
          this.loadPayable("");
        }).catch(error => {
        })
      },
      saveClick() {
        var _this = this;
        this.itemList = [];

        if (this.selectionChange.length === 0) {
          this.$message({ message: '请选择数据', type: 'warning' })
        } else {
          this.$confirm('对账金额为:'+_this.unpayAmount+'元，是否修改对账单？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.saveClicked = true;
            this.form.type = 1;
            try {
              this.selectionChange.forEach(item => {
                if (Number(item.submitAmount) <= 0) {
                  throw new Error()
                }
                const obj = {
                  amount: item.submitAmount,
                  createDate: item.createDate,
                  verifyItemId: item.id,
                  paymentPluginId: item.paymentPluginId,
                  paymentPluginName: item.paymentPluginName
                }
                this.itemList.push(obj)
              })
              this.form.itemList = this.itemList;
            } catch (e) {
              this.$message({ message: '付款金额出现负数，请核对', type: 'warning' })
              this.saveClicked = false
              return
            }
            delete this.form.supplierName;
            update(this.form).then(res => {
              _this.saveClicked = false;
              EventBus.$emit('supplierVerify-edit', res.data);
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                _this.$router.push({
                  path: '/supplierVerify/list'
                })
              })// 关闭当前tab回到列表
            }).catch(() => { this.saveClicked = false })
          });

        }
      },
      getSummaries(param) {
        this.$nextTick(() => {
          this.$refs.payableSupplierTable.doLayout()
        })
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总价'
            return
          }
          if (index === 2){
            return;
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return (Number(prev) + Number(curr)).toFixed(2)
              } else {
                return prev
              }
            }, 0)
            sums[index] += ' 元'
          }
        })

        return sums
      },
      toSearchSupplier(){
        this.times=new Date().getSeconds()
        this.supplierVisible=true
      },
      supplierClose(){
        this.supplierVisible = false;
      },
      beforeMount() {
        window.onresize = () => {
          return (() => {
            const h = document.documentElement.clientHeight || document.body.clientHeight
            if (this.queryType === false) {
              this.curHeight = h - 266// 减去页面上固定高度height
            } else {
              this.curHeight = h - 220// 减去页面上固定高度height
            }
          })()
        }
      },
      comeIn() {
        const h = document.documentElement.clientHeight || document.body.clientHeight
        this.curHeight = h - 220// 减去页面上固定高度height
      },
      chooseClick() {
        this.queryType = !this.queryType
        const h = document.documentElement.clientHeight || document.body.clientHeight
        if (this.queryType === false) {
          this.curHeight = h - 266// 减去页面上固定高度height
        } else {
          this.curHeight = h - 220// 减去页面上固定高度height
        }
      },
      selectSupplier(val){debugger
        if(val == '#'){
          this.form.supplierId = '';
          this.suppVisible = true;
        }
        this.supplierName=val.name;
        this.form.supplierId=val.id;
        this.loadPayable("");
      },
      remoteMethod(query) {
        this.loadSupplier(query)
      },
      loadSupplier(query) {
        let params = new URLSearchParams()
        params.append('name', query)
        supplierList(params).then(res => {
          this.suppliers = res.data.data
        })
      }
    }
  }
</script>

<style scoped>

  body .el-table th.gutter {
    display: table-cell !important
  }
  .elOption{
    background-color: #909399;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 50%;
    height: 40px
  }
  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #eeeeee;
  }

  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/.el-header {
          padding: 10px;
          /* height: 100% !important; */
          padding-bottom: 0;
        }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
  }
  .report_header_left {
    width: 5px;
    height: 100%;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }

  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }
  .report_header_date {
    margin-left: 10px;
    width: 250px;
    margin-top: 5px;
  }
  .report_body{
    padding-top: 10px;
    padding-bottom: 10px;
    margin-top: 5px;
  }
  .product_header_name {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-right: 20px;
    border-left: 5px #409EFF solid;
    margin-bottom: 20px;
    background-color: #f2f2f2;
  }
</style>
